<template>
  <view-box body-padding-bottom="55px" class="container" v-if="product">
    <swiper auto loop :aspect-ratio="800/800" v-if="product.attachments">
      <swiper-item v-for="(item, index) in product.attachments" :key="index"><img style="height:100%;" :src="item"></swiper-item>
    </swiper>
    <div class="p-base">
      <div class="p-price-group">
        <span class="p-shop-price">￥{{price}}</span>
        <s class="p-market-price">￥{{product.original_price}}</s>
        <span class="p-sales-count">已售{{salesCount}}件</span>
      </div>
    </div>
    <div class="p-name">
      {{product.name}}
    </div>
    <flexbox class="p-service" :gutter="0">
      <flexbox-item :span="1/3">
        <div class="p-service-item">
          <span><i class="iconfont icon-xuanze"></i> 七天退货</span>
        </div>
      </flexbox-item>
      <flexbox-item :span="1/3">
        <div class="p-service-item">
          <span><i class="iconfont icon-xuanze"></i> 48小时发货</span>
        </div>
      </flexbox-item>
      <flexbox-item :span="1/3">
        <div class="p-service-item">
          <span><i class="iconfont icon-xuanze"></i> 假一赔十</span>
        </div>
      </flexbox-item>
    </flexbox>
    <group  class="p-promotion clear-margin">
      <cell-box v-if="product.underway_flash_sale">
        <div class="p-promotion-item">
          <span class="tag">限时秒杀</span> 
          优惠￥{{product.underway_flash_sale.discount}}，
          <clocker :time="product.underway_flash_sale.ended_at" class="clock">
           %D天 <span>%H</span> : <span>%M</span> : <span>%S</span>
          </clocker>
        </div>
      </cell-box>
      <cell-box v-if="product.full_cut">
        <div class="p-promotion-item">
          <span class="tag">满减优惠</span> 
          <span class="full-cut" v-for="(cut, index) in product.full_cut" :key="index">满{{cut.amount}}减{{cut.price}}</span>
        </div>
      </cell-box>
      <cell-box @click.native="showTeamPopup = true" is-link v-if="product.underway_team_activity">
        <div class="p-promotion-item">
          <span class="tag">拼团购买</span> 拼团购买可优惠￥{{product.underway_team_activity.discount}}
        </div>
      </cell-box>
    </group>
    <flexbox v-if="product.underway_team_activity" :gutter="0" class="active-found" v-for="(item, index) in recomendFounds" :key="index">
      <flexbox-item :span="3/8">
        <div class="team-user">
          <img :src="item.user.avatar" alt="">
          <span>{{item.user.name}}</span>
        </div>
      </flexbox-item>
      <flexbox-item :span="3/8">
        <div class="team-clock">
          <span>还差<span>{{item.needer - item.join}}人</span>拼成</span>
          <clocker :time="item.ended_at" class="clock">
           剩余%D天 %H : %M : %S
          </clocker>
        </div>
      </flexbox-item>
      <flexbox-item :span="2/8"> 
        <div class="team-btn">
          <x-button mini type="warn" @click.native="choiceSpec('team_activity', item.id)">去拼单</x-button>
        </div>
      </flexbox-item>
    </flexbox>
    <group class="clear-margin">
       <cell :title="'商品评价（' + product.comment_count + '）'" value="查看全部" is-link :link="'/comments/' + product.id"></cell>
    </group>
    <div class="p-comments-list">
      <div class="p-comments-item" :class="{'vux-1px-b' : product.comments.length !== index + 1}" v-for="(comment, index) in product.comments" :key="comment.id">
        <div class="p-comments-item-title">
          <img v-if="!comment.user.avatar" src="/static/thumb-small.png">
          <img v-else :src="comment.user.avatar">
          <span class="p-comments-item-name">{{comment.user.name}}</span>
          <span class="p-comments-item-time">{{comment.created_at}}</span>
        </div>
        <div class="p-comments-item-content">
          {{comment.content}}
        </div>
        <div class="p-comments-item-spec">
          <span data-reactid="280">{{comment.order_goods.spec_value}}</span>
        </div>
      </div>
    </div>
    <group class="clear-margin">
       <cell title="商品详情"></cell>
    </group>
    <div class="p-detail" v-html="product.content"></div>
    <div class="p-recommend-container" v-if="product.references && product.references.length > 0">
      <div class="p-recommend-title"><span><i class="iconfont icon-xing"></i> 为你推荐</span></div>
      <list :list="product.references"></list>
      <divider v-if="product.references.length > 1">我是有底线的</divider>
    </div>
    <div slot="bottom" class="action-bar vux-1px-b vux-1px-t">
      <div class="p-home-btn vux-1px-r" @click="$router.push('/')" v-if="!product.is_exchange">
        <span class="iconfont icon-shouye2"></span>
        <span>首页</span>
      </div>
      <div class="p-store-btn vux-1px-r" @click="collection()" v-if="!product.is_exchange">
        <span class="iconfont icon-shoucang"></span>
        <span>收藏</span>
      </div>
      <!-- <div class="p-chat-btn" @click="jump(qq)">
        <span class="iconfont icon-kefu" style="color:#e02e24;"></span>
        <span>客服</span>
      </div> -->
      <div class="p-direct-btn" @click="choiceSpec('buy_now', 0)" v-if="!product.is_exchange">
        <span class="p-price">￥{{price}}</span>
        <span>直接购买</span>
      </div>
      <div v-if="product.underway_team_activity" class="p-group-btn" @click="choiceSpec('team_activity', 0)">
         <span class="p-price">￥{{teamActivityPrice}}</span>
        <span>发起拼团</span>
      </div>
      <div v-else-if="!product.is_virtual && !product.is_exchange" class="p-cart-btn" @click="choiceSpec('add_cart', 0)">
        <span class="iconfont icon-gouwuche"></span>
        <span>加入购物车</span>
      </div>
      <div class="p-direct-btn bi" @click="choiceSpec('zhuangbi_buy', 0)" v-if="product.is_exchange">
        <span class="p-price">{{Math.ceil(price)}}装币</span>
        <span>装币兑换</span>
      </div>
       <div class="p-cart-btn bi" @click="choiceSpec('qingbi_buy', 0)" v-if="product.is_exchange">
        <span class="p-price">￥{{(price * 100 - product.qingbi_number * 100) / 100}}+{{product.qingbi_number}}轻币</span>
        <span>轻币兑换</span>
      </div>
    </div>
    <!-- popup -->
    <div v-transfer-dom>
      <popup v-model="showPopup" is-transparent v-if="product.id">
        <div class="sku-selector-head vux-1px-b">
          <img :src="thumb ? thumb : product.thumb_img">
          <div class="sku-selector-head-content">
            <div class="sku-actions">
              <div class="sku-selector-price" v-if="action === 'team_activity'">￥{{teamActivityPrice}}</div>
              <div class="sku-selector-price" v-else>￥{{price}}</div>
              <div class="sku-selector-desc">
                请选择 
                <span v-for="(item, index) in product.specs" :key="index">{{item.name}} </span>
                <span>数量 </span>
              </div>
              <div class="sku-selector-close-btn vux-close" @click="showPopup = false"></div>
            </div>
          </div>
        </div>
        <div class="pop-box">
          <div class="spec vux-1px-b" v-for="(spec, index) in product.specs" :key="index">
            <p class="spec-title">{{spec.name}}</p>
            <checker
            v-model="spec.checked"
            @on-change="onChange"
            radio-required
            default-item-class="popup-item"
            selected-item-class="popup-item-selected"
            disabled-item-class="popup-item-disabled">
              <checker-item :value="item.id" v-for="item in spec.items" :key="item.id" @click.native="changeThumb(item)" @on-item-click="onItemClick"> {{item.item}} </checker-item>
            </checker>
          </div>
          <div class="p-number">
            <span>数量<span class="stock">（库存 {{stock}}）</span></span>
            <inline-x-number class="number" :min="1" :max="stock" v-model="number" width="30px"></inline-x-number>
          </div>
        </div>
        <x-button class="btn" type="warn" @click.native="submit">确定</x-button>
      </popup>
    </div>
    <!-- teamPoup -->
    <div v-transfer-dom>
      <popup v-model="showTeamPopup" class="team-poup">
        <div class="emtpy" v-if="product.underway_team_activity && product.underway_team_activity.active_founds.length === 0">
          <empty tips="还没有人参与拼单" icon="icon-daipingjia"></empty>
          <x-button style="margin-top:80px;" class="btn" type="warn" @click.native="choiceSpec('team_activity', 0)">发起拼单</x-button>
        </div>
        <div class="team-poup-flex" v-if="product.underway_team_activity && product.underway_team_activity.active_founds.length > 0">
          <flexbox :gutter="0" class="active-found" v-for="(item, index) in product.underway_team_activity.active_founds" :key="index">
            <flexbox-item :span="3/8">
              <div class="team-user">
                <img :src="item.user.avatar" alt="">
                <span>{{item.user.name}}</span>
              </div>
            </flexbox-item>
            <flexbox-item :span="3/8">
              <div class="team-clock">
                <span>还差<span>{{item.needer - item.join}}人</span>拼成</span>
                <clocker :time="item.ended_at" class="clock">
                 剩余%D天 %H : %M : %S
                </clocker>
              </div>
            </flexbox-item>
            <flexbox-item :span="2/8"> 
              <div class="team-btn">
                <x-button mini type="warn" @click.native="choiceSpec('team_activity', item.id)">去拼单</x-button>
              </div>
            </flexbox-item>
          </flexbox>
        </div>
      </popup>
    </div>
  </view-box>
</template>
<script>
  import { TransferDom, Swiper, SwiperItem, Group, CellBox, Cell, Flexbox, FlexboxItem, Divider, ViewBox, Popup, Checker, CheckerItem, InlineXNumber, XButton, Clocker } from 'vux'
  import { SET_ACTION_TYPE, SET_BUY_NOW_LIST, SET_TEAM_FOUND_ID } from '@/store/mutation-types'
  import List from './components/List'
  import Empty from '@/views/components/Empty'
  import { QQ_KEFU_URL } from '@/config'
  export default {
    directives: {
      TransferDom
    },
    data () {
      return {
        qq: QQ_KEFU_URL,
        showPopup: false,
        showTeamPopup: false,
        number: 1,
        product: null,
        thumb: null,
        goods_id: null
      }
    },
    components: {
      Swiper,
      SwiperItem,
      Group,
      CellBox,
      Cell,
      Flexbox,
      FlexboxItem,
      Divider,
      List,
      ViewBox,
      Popup,
      Checker,
      CheckerItem,
      InlineXNumber,
      XButton,
      Clocker,
      Empty
    },
    mounted () {
      this.goods_id = this.$route.params.id
      this._getData()
    },
    watch: {
      '$route' (to, from) {
        if (this.$route.params.id !== this.goods_id) {
          this.goods_id = this.$route.params.id
          this._getData()
        }
      },
      goods_id (newValue) {
        this._history(newValue)
      }
    },
    computed: {
      salesCount () {
        if (typeof this.product.sales_count === 'number' && typeof this.product.start_sales_count === 'number') {
          return parseInt(this.product.sales_count + this.product.start_sales_count)
        }
        return 0
      },
      recomendFounds () {
        let list = []
        if (this.product.underway_team_activity && this.product.underway_team_activity.active_founds) {
          this.product.underway_team_activity.active_founds.forEach((item, index) => {
            if (index <= 1) {
              list.push(item)
            }
          })
        }
        return list
      },
      action () {
        return this.$store.state.cart.action
      },
      // 价格计算
      price () {
        let fDiscount = 0
        let price = 0
        // 限时秒杀
        if (this.product.underway_flash_sale) {
          fDiscount = this.product.underway_flash_sale.discount
        }
        // 规格价
        if (this.spec) {
          price = this.spec.price
        } else {
          price = this.product.price
        }
        if (fDiscount > 0) {
          price = (price * 100 - fDiscount * 100) / 100
        }
        if (price < 0) {
          price = 0
        }
        return price
      },
      teamActivityPrice () {
        let tDiscount = 0
        let price = 0
        // 拼团
        if (this.product.underway_team_activity) {
          tDiscount = this.product.underway_team_activity.discount
        }
        // 规格价
        if (this.spec) {
          price = this.spec.price
        } else {
          price = this.product.price
        }
        if (tDiscount > 0) {
          price = (price * 100 - tDiscount * 100) / 100
        }
        if (price < 0) {
          price = 0
        }
        return price
      },
      stock () {
        let stock = this.product.stock
        if (this.product.specs.length !== 0 && this.spec) {
          stock = this.spec.stock
        }
        if (stock <= 0) {
          stock = 0
        }
        return stock
      },
      // 已选择的规格
      spec () {
        if (this.product.specs) {
          let keys = []
          this.product.specs.forEach((el) => {
            el.checked && keys.push(el.checked)
          })
          keys.sort()
          if (keys.length === this.product.specs.length) {
            return this.product.spec_prices[keys.join('_')]
          }
        }
        return null
      }
    },
    methods: {
      choiceSpec (action, teamFoundId) {
        this.$store.commit(SET_ACTION_TYPE, action)
        this.$store.commit(SET_TEAM_FOUND_ID, teamFoundId)
        this.showPopup = true
        this.showTeamPopup = false
      },
      onItemClick (value, disabled) {
      },
      onChange (value, item) {
        console.log(this.spec)
      },
      changeThumb (item) {
        if (item.image) {
          this.thumb = item.image
        }
      },
      jump (url) {
        if (url) {
          location.href = url
        }
      },
      submit () {
        // 未选择规格
        if (this.product.specs.length > 0 && this.spec === null) {
          this.$vux.toast.show({
            text: '请选择规格',
            type: 'cancel'
          })
          return false
        }
        // 商品库存
        if (this.stock <= 0) {
          this.$vux.toast.show({
            text: '暂时缺货',
            type: 'cancel'
          })
          return false
        }
        this._handleSubmit()
      },
      collection () {
        this.$http.post('/collections', {collectionable_id: this.product.id, collectionable_type: 'App\\Goods'}).then((response) => {
          this.$vux.toast.show('收藏成功')
        }).catch((error) => {
          console.log(error)
        })
      },
      _handleSubmit () {
        if (this.action === 'add_cart') {
          let data = {goods_id: this.product.id, quantity: this.number, spec_goods_price_id: this.spec ? this.spec.id : 0}
          this.$store.dispatch('addToCart', data).then((response) => {
            console.log(response.data)
            this.$router.push('/carts')
          })
        }
        if (this.action !== 'add_cart') {
          let data = {
            id: null,
            goods_id: this.product.id,
            quantity: this.number,
            spec_goods_price_id: this.spec ? this.spec.id : 0,
            goods: this.product,
            spec: this.spec,
            checked: true
          }
          this.$store.commit(SET_BUY_NOW_LIST, data)
          this.$router.push('/checkout')
        }
      },
      _getData () {
        this.product = null
        this.$vux.loading.show()
        this.$http.get('/goods/' + this.goods_id + '?references=1').then((response) => {
          this.$vux.loading.hide()
          this.product = response.data
        }).catch((error) => {
          this.$vux.loading.hide()
          console.log(error)
        })
      },
      _history (goodsId) {
        let history = JSON.parse(localStorage.getItem('history'))
        history = history === null ? [] : history
        if (history.length < 20) {
          if (history.indexOf(goodsId) !== -1) {
            history.splice(history.indexOf(goodsId), 1)
          }
          history.unshift(goodsId)
        } else {
          if (history.indexOf(goodsId) === -1) {
            history.pop()
            history.unshift(goodsId)
          } else {
            history.splice(history.indexOf(goodsId), 1)
            history.unshift(goodsId)
          }
        }
        localStorage.setItem('history', JSON.stringify(history))
      }
    }
  }
</script>
<style scoped lang="less">
  .container {
    background-color:#f2f2f2;
  }
  .p-base {
    background: #fff;
    padding: 10px;
    line-height: 20px;
    height: 20px;
  }
  .p-price-group {
    color: #58595b;
    font-size: 14px;
  }
  .p-shop-price {
    color: @tabbar-text-active-color;
    font-size: 20px;
  }
  .p-market-price {
    padding-left: 5px;
  }
  .p-sales-count {
    float: right;
  }
  .p-name {
    background: #fff;
    color: #151516;
    font-weight: 600;
    text-align: justify;
    letter-spacing: 1px;
    line-height: 1.4;
    padding: 0 10px 10px 10px;
  }
  .p-service {
    background-color: #fff5fa;
    color: #58595b;
    text-align: center;
    padding: 15px 0;
  }
  .p-service .p-service-item span{
    font-size: 14px;
  }
  .p-service .p-service-item .iconfont {
    color: @tabbar-text-active-color;
  }
  .router-view .p-promotion .weui-cells {
    margin-top: 0;
  }
  .clear-margin {
    margin-top: -15px;
  }
  .p-promotion .p-promotion-item {
    font-size: 14px;
  }
  .p-promotion .p-promotion-item .tag {
    color: @tabbar-text-active-color;
    border: 1px solid @tabbar-text-active-color;
    border-radius: 2px;
    padding: 1px 3px;
    font-size: 12px;
    margin-right: 30px;
  }
   .p-promotion .p-promotion-item .full-cut {
    margin-right: 10px;
   }
  .p-comments-list {
    background: #fff;
    padding: 0 10px;
  }
  .p-comments-item {
    padding-top: 5px;
    padding-bottom: 15px;
  }
  .p-comments-item-title {
    height: 25px;
    margin: 10px 0;
    line-height: 25px;
  }
  .p-comments-item-title img {
    float: left;
    height: 25px;
    width: 25px;
    border-radius: 100%;
    margin-right: 7px;
    border: 1px solid #e0e0e0;
  }
  .p-comments-item-name {
    color: #151516;
    white-space: nowrap;
    -webkit-line-clamp: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-box-orient: vertical;
    text-align: left;
  }
  .p-comments-item-time {
    float: right;
    color: #9c9c9c;
    display: block;
    font-size: 13px;
  }
  .p-comments-item-content {
    width: 100%;
    max-height: 40px;
    color: #58595b;
    word-break: break-all;
    word-wrap: break-word;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    font-size: 14px;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-box-orient: vertical;
    text-align: left;
  }
  .p-comments-item-spec {
    font-size: 12px;
    color: #9c9c9c;
    margin-top: 7px;
    width: 100%;
    word-break: break-all;
    line-height: 1;
  }
  .p-detail {
    padding: 5px;
    background: #fff;
  }
  .p-detail img{
    max-width: 100% !important;
    display: block !important;
  }
  .p-recommend-title {
    height: 46px;
    line-height: 46px;
    font-size: 0;
    text-align: center;
  }
  .p-recommend-title span {
    display: inline-block;
    font-size: 14px;
    color: #ff7878;
  }
  .action-bar {
    position: fixed;
    bottom: 0;
    height: 54px;
    background: #fff;
    width: 100%;
    display: flex;
  }
  .action-bar span {
    display: block;
    text-align: center;
    line-height: 1;
  }
  .action-bar .iconfont {
    font-size: 20px;
    margin-bottom: 2px;
  }
  .p-home-btn, .p-store-btn, .p-chat-btn {
    width: 50px;
    padding-top: 8px;
    color: #58595b;
    font-size: 14px;
  }
  .p-direct-btn {
    flex:1;
    padding-top: 8px;
    background-color: #f3aba7;
    color: #fff;
    font-size: 15px;
  }
  .p-group-btn ,.p-cart-btn{
    flex: 1;
    padding-top: 8px;
    background-color: #e02e24;
    color: #fff;
    font-size: 15px;
  }
  .p-price {
    margin-bottom: 4px;
    font-weight: 500;
    font-size: 17px;
  }
  .bi .p-price {
    font-size: 12px;
    font-weight: normal;
    margin-bottom: 8px;
  }
  .sku-selector-head{
    position: relative;
    height: 110px;
    img {
      position: absolute;
      height: 100px;
      width: 100px;
      top: 0;
      left: 10px;
      border: 1px solid #fff;
      border-radius: 5px;
      z-index: 999;
    }
    .sku-selector-head-content {
      padding: 30px 0 0 0;
      .sku-actions {
        height: 50px;
        position: relative;
        background-color: #eee;
        padding-left: 120px;
        padding-top: 30px;
        .sku-selector-price {
          position: relative;
          height: 18px;
          margin-bottom: 5px;
          line-height: 1;
          font-size: 18px;
          color: #e02e24;
        }
        .sku-selector-desc {
          display: -webkit-box;
          text-overflow: ellipsis;
          overflow: hidden;
          font-size: 12px;
          line-height: 1;
          color: #151516;
          word-break: break-all;
          word-wrap: break-word;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        .sku-selector-close-btn {
          position: absolute;
          width: 30px;
          height: 30px;
          top: 10px;
          right: 0px;
        }
      }
    }
  }
  .pop-box {
    padding:10px;
    min-height:160px;
    background-color: #eee;
    .spec {
      .spec-title {
        padding: 5px 5px 5px 2px;color:#888;
      }
      .popup-item {
        background-color: #ddd;
        color: #222;
        font-size: 14px;
        padding: 5px 10px;
        margin-right: 10px;
        line-height: 18px;
        border-radius: 15px;
        margin-bottom: 10px;
      }
      .popup-item-selected {
        background-color: #FF3B3B;
        color: #fff;
      }
      .popup-item-disabled {
        color: #999;
      }
    }
    .p-number {
      line-height: 50px;
      height: 50px;
      span {
        padding: 5px 5px 5px 2px;color:#888;
      }
      .number {
        float: right;
        margin-top: 15px;
        background-color: #fff;
      }
      .stock {
        font-size: 13px;
      }
    }
  }
  .btn {
    border-radius: 0 !important;
  }
  .active-found {
    background: #fff;
    .team-user {
      img{
        margin: 5px 5px 5px 10px;
        vertical-align: middle;
        width: 40px;
        border-radius: 40px;
        line-height: 40px;
      }
    }
    .team-clock {
      span {
        font-size: 14px;
        span {
          color: red;
        }
      }
      .clock {
        color: #999;
      }
      font-size: 12px;
      text-align: center;
    }
    .team-btn {
      text-align: right;
      margin-right: 10px;
    }
  }
  .team-poup {
    background: #fff;
    .team-poup-flex {
      padding: 5px 0 50px 0;
    }
  }
</style>
